package com.battery.minapp.redis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * redis单机的jedis接口服务类
 */
@Component("redisService")
public class RedisServiceImpl {


    @Autowired
    private RedisUtil redisUtil;

    /**
     * 从缓存中删除指定的key
     *
     * @param keys
     */
    public void del(final String... keys) {
        try {
            for (int i = 0; i < keys.length; i++) {
                redisUtil.del(keys[i]);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断一个键是否存在于缓存中
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        Boolean result = false;
        try {
            return redisUtil.exists(key);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 向缓存中插入数据
     *
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(final String key, final String value, final int liveTime) {
        if (value == null)
            return;
        try {
            redisUtil.set(key, value);
            if (liveTime > 0) {
                redisUtil.expire(key, liveTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 从缓存中获取数据
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        String cacheValue = "";
        try {
            try {
                String cacheBytes = redisUtil.get(key);
                if (cacheBytes != null) {
                    return cacheBytes;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cacheValue;
    }


    /**
     * 让某个key 若干秒后过期
     *
     * @param key
     * @param seconds
     * @return
     */
    public Long expire(String key, Integer seconds) {
        Long success = 1L;
        try {
            success = redisUtil.expire(key, seconds);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return success;
    }

    /**
     * 当key不存在时，set一对key value
     *
     * @param key
     * @param value
     * @return
     */
    public Long setnx(String key, String value) {
        Long result = null;
        try {
            result = redisUtil.setnx(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }


}
